﻿using Common.ECS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LitJson;
using UnityEngine;

public class BehaviorSystem : System<BehaviorEntity>
{
    public static Dictionary<int, INodeHandler<BehaviorEntity>> NodeHandlers = new Dictionary<int, INodeHandler<BehaviorEntity>>();

    public static Dictionary<int, INodeDataSerializor> NodeDataSerilizors = new Dictionary<int, INodeDataSerializor>();

    public static Dictionary<int, ITaskDataSerializor> TaskDataSerilizors = new Dictionary<int, ITaskDataSerializor>();

    public override void OnInit()
    {
        BehaviorRegistor.RegisterNodeHandler(NodeHandlers);
        BehaviorRegistor.RegisterNodeDataSerilizor(NodeDataSerilizors);
        BehaviorRegistor.RegisterTaskDataSerilizor(TaskDataSerilizors);
    }

    public override void Excute()
    {
        for (int i = 0; i < Context.AllEntities.Count; i++)
        {
            ExcuteNode(Context.AllEntities[i], 
                ((NodeComponent)Context.AllEntities[i].Components[ComponentType.NodeComponent]).RootData);
        }
    }

    void ExcuteNode(BehaviorEntity entity, NodeData node)
    {
        if (NodeHandlers.ContainsKey(node.CurNodeType))
        {
            NodeHandlers[node.CurNodeType].ExcuteNode(entity,node);
        }
        else
        {
            DebugUtils.LogError("不包含"+ node.CurNodeType + "类型的节点处理");
        }
    }

    public INodeData SerializeNodeData(string jsonStr)
    {
        JsonData data = JsonMapper.ToObject (jsonStr);
        int temp = data["NodeType"].AsInt;
        return NodeDataSerilizors[temp].DeSerializeData(jsonStr);
    }
}